/**
 * @description: 员工首页
 *
 * @author ligang
 * @date 2018年7月9日 下午21:00:52
 * @version 1.0.0.1
 */
var staffHome = {

    accessToken : null ,
    departmentId : null ,
    staffId : null ,    
    cid : null ,
    openId : null ,
    ct : null ,

    init : function(accessToken){
        staffHome.accessToken = accessToken;
        return staffHome;
    },

    // 	绘制员工首页
    queryStaffHome : function(){
        var data = {
            staffToken : staffHome.accessToken
        };
        var url = staffHome.getPath() +"/aem/client/ajaxStaffHome";
        var e = JSON.parse(staffHome.syncAjax("post", url , data , false));

        if(e.status == "200"){
            var data = e.data;
            var staffInfo = data.staffInfo;
            var staffRecord = data.staffRecord;
            var staffRankings = data.staffRankings;
            var departmentRankings = data.departmentRankings;
            var aemNewest = data.aemNewest;
            var aemHots = data.aemHots;
            var isDisable = data.isDisable;
            
            staffHome.accessToken = staffInfo.staffToken;
            staffHome.staffId = staffInfo.id;
            staffHome.openId = staffInfo.openId;
            staffHome.cid = staffInfo.cid;
            staffHome.departmentId = staffInfo.departmentId;

            //用户信息
            $("#staff-name").html(staffInfo.name)
            $("#head-img").attr("src",staffInfo.headImg);

            //我的战绩
            staffHome.setCircleStyle('doneTask', staffRecord.finishTask / 100);
            $("#finish-task").html(staffRecord.finishTask);
            $("#accumulative-score").html(staffRecord.accumulativeScore);
            staffHome.setCircleStyle('defeat-opponent-circle', staffRecord.defeatOpponent / 100);
            $("#defeat-opponent").html(staffRecord.defeatOpponent);
            
            //邀请好友赚积分是否隐藏
            if(isDisable == 1){
            	$(".invite-friends").hide();
            	$(".join-task").css('width', "100%");
            }

            //本周英雄榜
            var staff_html_ = '';
            if(staffRankings != null){
            	for (var i = 0; i < 3; i++) {
            		var staffRanking = staffRankings[i];
            		if (staffRanking != null) {
            			staff_html_ += '<div data-v-43210d38="" data-v-7ed3d5b2="" class="hero-rank">'
            				+ '<img data-v-43210d38="" id="staff-img" src=" ' + staffRanking.headImg + '" class="avatar">'
            				+ '<p data-v-43210d38="" class="name">' + staffRanking.name + '</p>'
            				+ '<p data-v-43210d38="" class="address">' + staffRanking.parentDepName + '</p>'
            				+ '<p data-v-43210d38="" class="address">' + staffRanking.depName + '</p>'
            				+ '<p data-v-43210d38="" class="score">+'
            				+ '<span data-v-43210d38="">' + staffRanking.accumulativeScore + '</span> 积分'
            				+ '</p>'
            				if (i == 0){
            					staff_html_+='<img data-v-43210d38="" src="" class="rank-icon"></div>';
	                        } else if (i == 1){
	                        	staff_html_+= '<img data-v-43210d38="" src="" class="rank-icon"></div>';
	                    	} else if (i == 2){
	                    		staff_html_+='<img data-v-43210d38="" src="" class="rank-icon"></div>';
	                    	} else {
	                    		staff_html_+= '</div>';
	                    	}
            		}
            	}
            	$("#staff-ranking").append(staff_html_);
            } else {
            	$("#staff-ranking").append('<div class="more" style="margin-bottom:40px;width: 100%">暂无数据</div>');
            }

            //部门排行榜
            var dep_html_ = '';
            if(departmentRankings != null){
            	for (var i = 0; i < 3; i++) {
            		var departmentRanking = departmentRankings[i];
            		if (departmentRanking != null) {
            			dep_html_ += '<div data-v-f534367c="" data-v-7ed3d5b2="" class="department-rank">';
            				if(i == 0){
            					dep_html_ +='<img data-v-f534367c="" src="" class="number">';
            					dep_html_ +='<div data-v-f534367c="" class="department-icon-wrap">';
            					dep_html_ +='<img data-v-f534367c="" src="" class="department-icon">';
            					dep_html_ +='<img data-v-f534367c="" src="" class="department-rank-icon">';
            					dep_html_ +='</div>';
            				}
            				if(i == 1){
            					dep_html_ +='<img data-v-f534367c="" src="" class="number">';
            					dep_html_ +='<div data-v-f534367c="" class="department-icon-wrap">';
           						dep_html_ +='<img data-v-f534367c="" src="" class="department-icon">';
            					dep_html_ +='<img data-v-f534367c="" src="" class="department-rank-icon">';
            					dep_html_ +='</div>';
            				}
            				if(i == 2){
            					dep_html_ +='<img data-v-f534367c="" src="" class="number">';
            					dep_html_ +='<div data-v-f534367c="" class="department-icon-wrap">';
           						dep_html_ +='<img data-v-f534367c="" src="" class="department-icon">';
            					dep_html_ +='<img data-v-f534367c="" src="" class="department-rank-icon">';
            					dep_html_ +='</div>';
            				}
            				dep_html_ +='<div data-v-f534367c="" class="info">';
            				dep_html_ +='<p data-v-f534367c="" class="depart-name">' + departmentRanking.departmentName + '</p></div>';
            				dep_html_ +='<p data-v-f534367c="" class="depart-score">+';
            				dep_html_ += '<span data-v-f534367c="">' + departmentRanking.depAvgScore + '</span>积分/人';
            				dep_html_ +='</p>';
            				dep_html_ +='</div>';
            			
            		}
            	}
            	$(".department-list").append(dep_html_);
            }else{
            	$(".department-list").append('<div class="more" style="margin-bottom:40px">暂无数据</div>');
            }

            //最新任务
            var aem_Newest_html_ = '';
            if(aemNewest == null){
            	$(".new-activity-wrap").hide();
            } else {
            	aem_Newest_html_ += '<div data-v-580431b3="" class="activity-thumb" attr-join="' + aemNewest.isJoin + '" onclick="staffHome.checkTask(this);" attr-url="' 
					+ aemNewest.url + '" attr-cid="' + aemNewest.cid + '" attr-id="' + aemNewest.id + '" attr-level="' 
					+ aemNewest.countShareLevel + '" attr-mgiId="' + aemNewest.mgiId + '" attr-click="' + aemNewest.clickSore + '" attr-share="' + aemNewest.shareScore + '" attr-asrId="' + aemNewest.asrId + '">'																																																																						
					+ '<img data-v-580431b3="" class="thumb" src="' + aemNewest.pic + '">'
					+ '<p data-v-580431b3="" class="title">' + aemNewest.name + '</p>'
					+ '<p data-v-580431b3="" class="time">任务时间：' + aemNewest.startTime.substring(0 , aemNewest.startTime.length - 5) + ' 至 ' + aemNewest.endTime.substring(0 , aemNewest.startTime.length - 5) + '</p>'
					+ '<p data-v-580431b3="" class="is-join '+ aemNewest.isJoin +'">' + aemNewest.join +  '</p>'
					+ '</div>';
            	$("#activity").append(aem_Newest_html_);
            }

            //热门任务
            if(aemHots != null){
            	var aem_html_ = '';  
            	for(var i = 0 ; i < aemHots.length ; i ++){
            		if(aemHots[i] != null){
            			aem_html_ += '<div data-v-580431b3="" class="activity-thumb" attr-join="' + aemHots[i].isJoin + '" onclick="staffHome.checkTask(this);" attr-url="' 
            			+ aemHots[i].url + '" attr-cid="' + aemHots[i].cid + '" attr-id="' + aemHots[i].id + '" attr-level="' 
            			+ aemHots[i].countShareLevel + '" attr-mgiId="' + aemHots[i].mgiId + '" attr-click="' + aemHots[i].clickSore + '" attr-share="' + aemHots[i].shareScore + '" attr-asrId="' + aemHots[i].asrId + '">'																																																																						
            			+ '<img data-v-580431b3="" class="thumb" src="' + aemHots[i].pic + '">'
            			+ '<p data-v-580431b3="" class="title">' + aemHots[i].name + '</p>'
            			+ '<p data-v-580431b3="" class="time">任务时间：' + aemHots[i].startTime.substring(0 , aemHots[i].startTime.length - 5) + ' 至 ' + aemHots[i].endTime.substring(0 , aemHots[i].startTime.length - 5) + '</p>'
            			+ '<p data-v-580431b3="" class="is-join ' + aemHots[i].isJoin + '">' + aemHots[i].join +  '</p>'
            			+ '</div>';
            		}
            	}
            	$("#activity-list").append(aem_html_); 
            }else{
            	$(".hot-activity-wrap").hide();
            }
        }
    },
    //查询员工登陆状态
    staffLoginStatus : function(){
    	var data = {
   			 accessToken : staffHome.accessToken
   	 	};
    	var getLoginStatus = staffHome.getPath() +"/aem/client/findStaffLoginStatus";
    	var staffInfo = JSON.parse(staffHome.syncAjax("post", getLoginStatus , data , false));
    	if(staffInfo.status=="200"){
    		staffInfo=staffInfo.data;
    		if(staffHome.StringEmpty(staffInfo)&&staffInfo.isFirstLogin==0){
       		 $(".gray").show();
    		}
	   	 }else{
	   		staffInfo=null;
	   	 }
    },
    //初始化弹框
    initInvite : function(){
    	 var data = {
    			 accessToken : staffHome.accessToken
    	 };
    	 var getInviteUrl = staffHome.getPath() +"/aem/client/findInviteInfo";
    	 var inviteInfo = JSON.parse(staffHome.syncAjax("post", getInviteUrl , data , false));
    	 if(inviteInfo.status=="200"){
    		 inviteInfo=inviteInfo.data;
    	 }else{
    		 inviteInfo=null;
    	 }
    	 var fansInfo = "<div class='task-tt'>邀请粉丝送积分</div> <div class='task-item-ct'>";
    	 var memberInfo = "<div class='task-tt'>邀请会员送积分</div> <div class='task-item-ct'>";
    	 if(staffHome.StringEmpty(inviteInfo)){
    		 for(var i=0;i<inviteInfo.length;i++){
    			 var userInviteData = inviteInfo[i];
    			 if(staffHome.StringEmpty(userInviteData)&&userInviteData.type==1){
    				//限制时间
    				if(userInviteData.isAstrictTime==1){
    					fansInfo += staffHome.timeFormat(userInviteData.startTime);
    					fansInfo +="至"
    					fansInfo += staffHome.timeFormat(userInviteData.endTime)+",";
    				}
    				//邀请奖励
    				if(staffHome.StringEmpty(userInviteData.inviteCount)&&staffHome.StringEmpty(userInviteData.inviteScore)){
    					fansInfo +="邀请"+userInviteData.inviteCount+"人关注公众号可得"+userInviteData.inviteScore+"积分";
    				}
    				//超出奖励
    				if(staffHome.StringEmpty(userInviteData.overCount)&&staffHome.StringEmpty(userInviteData.overInviteCount)){
    					fansInfo +="，超过"+userInviteData.overCount+"人，"+"每邀请"+userInviteData.overInviteCount+"人可获得"+userInviteData.overInviteScore+"积分";
    				}
    				fansInfo +="</div></div>";
    				$(".invite-fans").html(fansInfo);
    			 }else if(staffHome.StringEmpty(userInviteData)&&userInviteData.type==2){
    				//限制时间
    				if(userInviteData.isAstrictTime==1){
    					memberInfo += staffHome.timeFormat(userInviteData.startTime);
    					memberInfo +="至"
    					memberInfo += staffHome.timeFormat(userInviteData.endTime)+",";
    				}
    				//初始化会员奖励
    				//邀请奖励
    				if(staffHome.StringEmpty(userInviteData.inviteCount)&&staffHome.StringEmpty(userInviteData.inviteScore)){
    					memberInfo +="邀请"+userInviteData.inviteCount+"人新建会员可得"+userInviteData.inviteScore+"积分";
    				}
    				//超出奖励
    				if(staffHome.StringEmpty(userInviteData.overCount)&&staffHome.StringEmpty(userInviteData.overInviteCount)){
    					memberInfo +="，超过"+userInviteData.overCount+"人，"+"每邀请"+userInviteData.overInviteCount+"人可获得"+userInviteData.overInviteScore+"积分";
    				}
    				memberInfo +="</div></div>";
    				$(".invite-member").html(memberInfo);
    			 }
    		 }
    	 }
    },
   //时间格式化
    timeFormat : function (date){
    	var day = new Date(date);
    	var y = day.getFullYear();    
    	var m = day.getMonth()+1;//获取当前月份的日期   
    	var d = day.getDate();
    	var strDate = y+"年"+m+"月"+d+"日";
    	return strDate;
    },
    //判断字符串是否为空
    StringEmpty : function(content) {
        if (content == undefined || content == "" || content == null) {
            return false;
        } else {
            return true;
        }
    },

    // aemTask.getPath()
    getPath : function(){
        var parse = staffHome.parseUrl(window.location.href);
        var path = parse.protocol + '://' + parse.host + ':' + parse.port;
        if("scrm_sps" == parse.segments[0]){
            path +=  '/' + parse.segments[0];
        }
        return path;
    },

    trim : function(str) {
        return str.replace(/(^\s+$)/g, "");
    },

    /**
     * 发送ajax请求
     *
     * type_ : post or get
     * url_ : url
     * data_ : data_
     * async_ : sync type ,true or false
     */
    syncAjax : function(type_, url_, data_  , async_) {
        var msg_ = null;
        $.ajax({
            dataType : "text",
            type : type_,
            url : url_,
            data : data_,
            async : async_,
            success : function(msg) {
                msg_ = msg;
            },
            error : function(msg) {
                msg_ = msg;
            }
        });
        return msg_;
    },

    parseUrl : function(url) {
        var a =  document.createElement('a');
        a.href = url;
        return {
            source: url,
            protocol: a.protocol.replace(':',''),
            host: a.hostname,
            port: a.port,
            query: a.search,
            params: (function(){
                var ret = {},
                    seg = a.search.replace(/^\?/,'').split('&'),
                    len = seg.length, i = 0, s;
                for (;i<len;i++) {
                    if (!seg[i]) { continue; }
                    s = seg[i].split('=');
                    ret[s[0]] = s[1];
                }
                return ret;
            })(),
            file: (a.pathname.match(/\/([^\/?#]+)$/i) || [,''])[1],
            hash: a.hash.replace('#',''),
            path: a.pathname.replace(/^([^\/])/,'/$1'),
            relative: (a.href.match(/tps?:\/\/[^\/]+(.+)/) || [,''])[1],
            segments: a.pathname.replace(/^\//,'').split('/')
        };
    },

    //我的任务
    aemList : function () {
        window.location.href= staffHome.getPath() + '/aem/client/aemTaskList?accessToken=' + staffHome.accessToken +'&staffId=' + staffHome.staffId + '&cid=' + staffHome.cid + "&type=allTask";
    },

    //我的二维码
    invitingFriends : function () {
        window.location.href= staffHome.getPath() + '/aem/client/personalQrcode?cid=' + staffHome.cid;
    },

    //员工排行页
    staffRanking : function () {
        window.location.href= staffHome.getPath() + '/aem/client/personalRanking?cid=' + staffHome.cid;
    },

    //部门排行页
    departmentRanking : function () {
        window.location.href= staffHome.getPath() + '/aem/client/departmentRankingH5?cid=' + staffHome.cid;
    },
    
    //个人中心
    personalcenter : function () {
        window.location.href= staffHome.getPath() + '/aem/person/personalcenter?cid=' + staffHome.cid;
    },
    
    checkTask : function(o){
		var url = $(o).attr("attr-url") + "?cid=" + $(o).attr("attr-cid") + "&aemId=" + $(o).attr("attr-id") + "&level=1" + "&mgiId="  + $(o).attr("attr-mgiId")
							+"&openId=" + staffHome.openId +"&parentOpenId=null&staffId=" + staffHome.staffId + "&departmentId=" + staffHome.departmentId;    
		if($(o).attr("attr-join") == "has-join"){
			window.location.href = url + "&asrId=" + $(o).attr("attr-asrId");
		}else{
			$(".aem-join-gray").show();
			$("#aem-join-dialog").show();
			$("#span-share-score").text($(o).attr("attr-share"));
			$("#span-click-score").text($(o).attr("attr-click"));
			staffHome.ct = o;
			staffHome.aemUrl = url;
		}
	},
	
	// 弹窗关闭
	dialogClose : function(){
		$(".aem-join-gray").hide();
		staffHome.ct = null;
		staffHome.aemUrl = null;
	},
	
	// 接受任务
	acceptTask : function(){ 
		var o = staffHome.ct;
		var data={
				cid : $(o).attr("attr-cid"),
				aemId : $(o).attr("attr-id"),
				level : $(o).attr("attr-level"),
				mgiId : $(o).attr("attr-mgiId"),
				openId : staffHome.openId,
				userIdentity:3,								// 用户身份 3.员工
				staffId : staffHome.staffId, 
				spreadType:1
		}
		var url = staffHome.getPath() +"/aem/client/ajaxClientJoinAemTask"; 
		var e = JSON.parse(staffHome.syncAjax("post", url , data , false)); 
		if(e.status == "200"){
			window.location.href = staffHome.aemUrl + "&asrId=" + e.asr.id;
		}
	},
	setCircleStyle: function(id, percent){
		if(isNaN(percent)){
			percent = 0;
		}
		var dashOffset = (1 - percent) * Math.PI * 100;
		var circle = document.getElementById(id);
		circle.setAttribute('stroke-dashoffset', dashOffset);
	}
}



















